/**
 * 滑动窗口（双指针）
 * @param {string} answerKey
 * @param {number} k
 * @return {number}
 */
export var maxConsecutiveAnswers = function (answerKey, k) {
  function maxConsecutiveAnswersCh(ch) {
    let res = 0
    let left = 0
    let right = 0
    let chIndex = []

    while (right < answerKey.length) {
      if (answerKey[right] == ch) {
        chIndex.push(right)
        if (chIndex.length > k) {
          left = chIndex.shift() + 1
        }
      }
      res = Math.max(res, right - left + 1)
      right++
    }
    return res
  }
  return Math.max(maxConsecutiveAnswersCh('T'), maxConsecutiveAnswersCh('F'))
}

/**
 * 滑动窗口（双指针）
 * @param {string} answerKey
 * @param {number} k
 * @return {number}
 */
export var maxConsecutiveAnswers2 = function (answerKey, k) {
  let res = 0
  let right = 0
  let tleft = 0
  let fleft = 0
  let tChIndex = []
  let fChIndex = []

  while (right < answerKey.length) {
    if (answerKey[right] == 'F') {
      fChIndex.push(right)
      if (fChIndex.length > k) {
        fleft = fChIndex.shift() + 1
      }
    }
    if (answerKey[right] == 'T') {
      tChIndex.push(right)
      if (tChIndex.length > k) {
        tleft = tChIndex.shift() + 1
      }
    }
    const left = Math.min(tleft, fleft)
    res = Math.max(res, right - left + 1)
    right++
  }
  return res
}

/**
 * @param {string} answerKey
 * @param {number} k
 * @return {number}
 */
const T = 'T'.charCodeAt(0),
  F = 'F'.charCodeAt(0)
export var maxConsecutiveAnswers3 = function (answerKey, k) {
  let ans = 0
  for (let left = 0, right = 0, cntsT = 0, cntsF = 0; right < answerKey.length; right++) {
    cntsT += answerKey.charCodeAt(right) === T ? 1 : 0
    cntsF += answerKey.charCodeAt(right) === F ? 1 : 0
    while (cntsT > k && cntsF > k) {
      cntsT -= answerKey.charCodeAt(left) === T ? 1 : 0
      cntsF -= answerKey.charCodeAt(left) === F ? 1 : 0
      left++
    }
    ans = Math.max(ans, right - left + 1)
  }
  return ans
}
